import { s_getcommontableinfo, s_operateInfo, s_updateInfo, state2text, status2text } from "@/services/basis";
import { ActionType, ProCard, ProColumns, ProForm, ProFormDigit, ProFormInstance, ProFormMoney, ProFormRadio, ProFormText, ProTable } from "@ant-design/pro-components";
import { Button, Col, message, QRCode, Row, Space, Tabs, TabsProps, Tag, Typography } from "antd";
import { useRef, useState } from "react";

const App:React.FC=()=>{
   const [inviteCode,setInviteCode]=useState('邀请后生成');
   const [selectedRecord,setSelectedRecord]=useState<DataType[]>([]);

   const form_ref=useRef<ProFormInstance>();
   const mtable_ref=useRef<ActionType>();

   interface DataType{
      // x_id,invite_code,name,mobilephone,state,status,operate_time,invite_time,invite_enddate
      x_id:number,invite_code:string,name:string,mobilephone:string,state:number,status:number,
      operate_time:string,invite_time:string,invite_enddate:string,invite_xid:number,x_type:number,
   };

   const columns:ProColumns<DataType>[]=[
      {dataIndex:'x_id',title:'XID'},
      {dataIndex:'x_type',title:'伙伴类型',
         render:(text)=>text==1?<Tag>供应商</Tag>:text==2?<Tag>客户</Tag>:<Tag>全方位伙伴</Tag>,
      },
      {dataIndex:'invite_code',title:'邀请码'},{dataIndex:'name',title:'邀请公司名'},
      {dataIndex:'mobilephone',title:'手机号'},{dataIndex:'invite_time',title:'邀请时间',valueType:'date'},
      {dataIndex:'invite_enddate',title:'到期时间',valueType:'date'},{dataIndex:'operate_time',hidden:true},
      {dataIndex:'state',title:'进度',render:(text:any)=>state2text(1,text),fixed:'right'},
      {dataIndex:'status',title:'状态',render:(text:any)=>status2text(text),fixed:'right'},
      {dataIndex:'invite_xid',hidden:true},
   ];

   const tab_invite=<>
   <ProForm submitter={false} layout="horizontal" labelCol={{span:5,offset:0}} labelWrap labelAlign="left"
          onFinish={()=>invite()}
          formRef={form_ref}
       >
        <Row gutter={8}>
            <Col span={8}>
            </Col>
            <Col span={8}>
            <ProFormText name='name' label='伙伴名称'  width={300}
               rules={[{required:true,message:'必输项'}]}/>
            <ProFormDigit name='mobilephone' label='手机号' width={300} 
               rules={[{required:true,message:'必输项'}]}
             />
            <ProFormRadio.Group name='x_type' label='类型' 
               rules={[{required:true,message:'必输项'}]}
               options={[{value:1,label:'我的供应商'},{value:2,label:'我的客户'},{value:3,label:'全方位伙伴'}]}
               />
            <Space><QRCode value='https://www.hao123.com' />网页注册<QRCode value="https://xxxxd...dd."/>小程序注册</Space><br/>
            请将注册码发给您所邀请的伙伴（有效期7天）：<Typography.Title style={{color:'blue'}}>{inviteCode}</Typography.Title>
            <Space>
               <Button style={{width:300}} onClick={()=>form_ref.current?.submit()}>邀请注册</Button>
               <Button onClick={()=>form_ref.current?.resetFields()}>新邀请</Button>
            </Space>
            </Col>
        </Row>
           
        </ProForm>
   </>;

   const tab_list=<>
      <ProCard extra={<Space>
         <Button onClick={()=>operateInfo(5)}>确认准入</Button>
         <Button onClick={()=>operateInfo(4)}>拒绝准入</Button>
         <Button onClick={()=>operateInfo(2)}>冻结</Button>
         <Button onClick={()=>operateInfo(3)}>删除</Button>
         <Button onClick={()=>operateInfo(0)}>恢复</Button>
      </Space>}>
       <ProTable<DataType>
         actionRef={mtable_ref}
         rowKey='x_id'
         rowSelection={{
            type:'radio',
            onChange(selectedRowKeys, selectedRows, info) {
               setSelectedRecord(selectedRows);
            },
         }}
         columns={columns}
         request={async ()=>{
            const x=await s_getcommontableinfo({source:'v_sys_regist',x_id:1,id:0});
            return {
               data:x.data[0],
               success:true,
            }
         }}
         />
         </ProCard>
   </>;

   const tabItems:TabsProps['items']=[
      {
         key:'invite',
         label:'我要邀请',
         children:tab_invite,
      },
      {
         key:'list',
         label:'我已邀请列表',
         children:tab_list,
      }
   ];
    
   // 检查后台，并生成注册码
    async function invite(){
      const fdata=form_ref.current?.getFieldsValue();
      //  alert(JSON.stringify(fdata));
      const x=await s_updateInfo({source:'invite_sys_regist',x_id:1,id:0,operate_id:1,fdata});
      // alert(JSON.stringify(x.data[0][0].invitecode));
      if(x.success){
         message.success('邀请成功。请把邀请码发给伙伴。');
         setInviteCode(x.data[0][0].invitecode);
         form_ref.current?.setFieldValue('x_type',x.data[0][0].x_type);
      }else
         message.error('邀请失败，请联系管理员');
    }

   //  操作单据
    async function operateInfo(n:number){
        // source,x_id,operater_id,otype,id
        if(selectedRecord.length==0)
           message.warning('请选择要操作的行');
        else{
         const x=await s_operateInfo({x_id:1,source:'sys_regist',operater_id:1,otype:n,
            id:selectedRecord[0].x_id});
         if(x.success){
           message.success('操作成功');
           mtable_ref.current?.reloadAndRest?.();
         }else
           message.error('操作错误，请联系管理员。');
        }
     }

   //  主界面==========================================================================================================
    return <>
    
    <ProCard title='邀请伙伴注册' >
        <Tabs items={tabItems} />
        
    </ProCard>
    </>;
}

export default App;